# -*- encoding=utf-8 -*-

import requests
from build_log import Log

logger = Log()


def do_requests(method, url, body=None, timeout=30, obj=None):
    """
    http request
    :param method: http method
    :param url: http[s] schema
    :param body: json
    :param timeout: second
    :param obj: callback object, support list/dict/object
    :return:
    """
    try:
        if method.lower() not in ["get", "post", "put", "delete"]:
            return -1

        func = getattr(requests, method.lower())
        rs = func(url, json=body, timeout=timeout)

        if rs.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.no_content]:
            return 1

        if obj is not None:
            if isinstance(obj, list):
                obj.extend(rs.json())
            elif isinstance(obj, dict):
                obj.update(rs.json())
            elif callable(obj):
                obj(rs)
            elif hasattr(obj, "cb"):
                getattr(obj, "cb")(rs.json())
        return 0
    except Exception as e:
        logger.warning("requests {} ssl exception, {}".format(url, e))
        return -2
